package us.esme.lib

/*
 * Copyright 2008 WorldWide Conferencing, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 */


import net.liftweb._
import http._
import js._
import JE._
import JsCmds._
import SHtml._
import S._
import util._
import Helpers._
import sitemap._
import Loc._

import us.esme._
import model._

import scala.xml.{NodeSeq}

object Auth {
  def loggedIn_? = User.loggedIn_?
  
  val ifIsLoggedIn = If(loggedIn_? _, "You must be logged in")

  val menuItems =
  Menu(Loc("authToken", List("auth", "index"), "Manage Tokens", 
           Snippet("auth", doAuth _),
           ifIsLoggedIn)) :: Nil

  def doAuth(in: NodeSeq): NodeSeq = {
    val spanName = S.attr("span_id") openOr "NA"
    val formNodes: NodeSeq = findNode(<auth:form/>, in).map(_.child) openOr NodeSeq.Empty
    val span = findNode(<auth:span/>, in).map(_.child) openOr NodeSeq.Empty
    val list = findNode(<auth:list/>, in).map(_.child) openOr NodeSeq.Empty
    val theInput = "theName"
    val user = User.currentUser.open_! // we have a guard in the Loc so we know the user's logged in

    def addAuthToken(desc: String): JsCmd =
    desc.trim match {
      case x if x.length < 3 => S.error("Description too short")
        Noop

      case x => AuthToken.create.description(x).user(user).saveMe
        S.notice("New token added")
        redisplayTokens & SetValById(theInput, "")
    }

    def redisplayTokens: JsCmd = SetHtml(spanName, displayTokens)

    def displayTokens: NodeSeq = {
      def doLoop(toBind: NodeSeq): NodeSeq =
      user.authTokens.flatMap(t => bind("auth", toBind,
                                        "description" -> t.description, 
                                        "token" -> t.uniqueId,
                                        "remove" -> 
                                        ajaxButton(?("Revoke"),
                                                   () => {t.delete_!
                                                          redisplayTokens})))
    
      bind("auth", list, "item" -> doLoop _)
    }

    bind("auth", span, "list" -> ((_: NodeSeq) => displayTokens)) ++
    ajaxForm(bind("auth",
                  formNodes,
                  "text" -> text("", addAuthToken, "id" -> theInput)))
  }
}
